<template>
  <div class="goods" :class="{ presale: isPreSale && !view }" @click="handleGoTo">
    <div class="goods-img">
      <el-image style="width: 188px; height: 189px" :src="gInfo.imgSrc" fit="cover"></el-image>
      <span v-if="isPreSale" class="goods-tag" :class="`goods-tag__${gInfo.state}`">{{ gInfo.stateDisplay
        }}</span>
      <span v-if="view" class="goods-tag" :class="`goods-tag__${gInfo.actionType}`">{{ gInfo.actionTypeDisplay
        }}</span>
    </div>
    <div class="goods-title">
      <el-text style="--el-text-font-size: var(--el-font-size-medium);color: var(--jbc-font-color)" line-clamp="2">{{
        gInfo.title }}</el-text>
    </div>
    <div class="goods-presale" v-if="isPreSale && !view">
      <div>预售时间：{{ gInfo.timeRange }}</div>
      <el-text tag="div" truncated>
        预售区域：{{ gInfo.areaNames }}
      </el-text>
    </div>
    <div class="goods-footer">
      <div class="goods-price" :class="{ normal: !gInfo.price }">{{ $numberPriceDisplay(gInfo.price) }}</div>
      <div class="goods-btn" v-if="gInfo.valId" @click.stop="handleDelLike">
        <el-button color="#D6000F" circle>
          <el-icon>
            <Delete />
          </el-icon>
        </el-button>
      </div>
      <div class="goods-btn" v-else-if="!isPreSale" @click.stop="handleAddShopCar">
        <el-button :color="!isDisabled ? '#D6000F' : '#999999'" :disabled="isDisabled" circle>
          <svg-icon class-name="shop-car" icon-class="jbcshop" />
        </el-button>
      </div>
    </div>

    <custom-dialog v-if="!isPreSale" title="加入购物车" width="500" custom-class="custom-web" v-model="state.isVisible"
      :disabled="state.disabled" @close="handleCommand('close', $event)">
      <el-form ref="countFormRef" label-width="80px" :model="countForm" :rules="countRules">
        <el-form-item label="商品名称" prop="count">
          {{ gInfo.title }}
        </el-form-item>
        <el-form-item label="商品单价" prop="count">
          {{ $numberPriceDisplay(gInfo.price) }}
        </el-form-item>
        <el-form-item label="商品数量" prop="count">
          <el-input-number style="margin: 0 10px; width: 100%;" size="large" v-model="countForm.count" :min="1"
            :max="item.inventory" />
        </el-form-item>
        <el-button size="large" color="#D6000F" style="width:100%;margin-top: 20px;" :loading="countLoading"
          @click.prevent="countFormSubmit">确定</el-button>
      </el-form>
    </custom-dialog>
  </div>
</template>
<script setup name="goods">
import { ShoppingCart } from '@element-plus/icons-vue'
import { appViewAddCarsGet } from '@/api/goods'
import { appPersonalDelLikeGet } from '@/api/account'
import { dialogCustomStyle } from '@/components/webCustom/utils'
import useShoppingCartStore from '@/components/webCustom/shoppingCart'
import { dayjs } from 'element-plus'
import { computed } from 'vue'
const stateMap = {
  0: '待开启',
  1: '进行中',
  2: '已结束',
  3: '已参加'
}
const actionTypeMap = {
  1: '商品',
  2: '预售',
  3: '分货'
}
const actionTypeNameMap = {
  1: 'goods',
  2: 'preSaleGoods',
  3: 'activityDetail'
}
const emit = defineEmits(['reload'])
const { proxy } = getCurrentInstance()
const props = defineProps({
  item: {
    type: Object,
    default: () => ({}),
  },
  type: {
    type: String,
    default: 'goods',
  },
  index: {
    type: Number,
    default: 0,
  },
  view: {
    type: Boolean,
    default: false,
  }
})
const router = useRouter()
const isPreSale = computed(() => {
  return props.type === 'preSale'
})
const gInfo = computed(() => {
  const d = {}
  d.valId = props.item.valId || ''
  d.id = props.item.id
  if (props.view) {
    d.imgSrc = props.item.pic || props.item.coverimgurl
    d.title = props.item.name || props.item.title
    d.price = props.item.price
    d.actionTypeDisplay = actionTypeMap[props.item.actionType]
    d.actionType = props.item.actionType
  } else if (props.type === 'goods') {
    d.imgSrc = props.item.coverimgurl
    d.price = props.item.price
    d.title = props.item.title
  } else {
    d.imgSrc = props.item.pic || props.item.coverimgurl
    d.title = props.item.name || props.item.title
    d.areaNames = props.item.areaNames
    d.timeRange = props.item.stime && props.item.etime ? `${dayjs(props.item.stime).format('YYYY.MM.DD')}~${dayjs(props.item.etime).format('YYYY.MM.DD')}` : ''
    if (props.item.buy) {
      props.item.state = 3
    }
    d.stateDisplay = stateMap[props.item.state]
    d.state = props.item.state
    d.price = 0
  }
  return d
})
const handleGoTo = () => {
  let to = ''
  if (props.view) {
    to = actionTypeNameMap[props.item.actionType]
  } else {
    to = props.type === 'goods' ? 'goods' : 'preSaleGoods'
  }
  router.push({
    name: to,
    params: {
      id: props.item.valId || props.item.id,
    },
  })
}
const handleAddShopCar = () => {
  handleCommand('addShopCar', props.item)
}
const handleDelLike = () => {
  proxy.$modal.confirm('<div style="display: flex;align-items: center;font-size: 16px;color: #323232;line-height: 21px;">' + '确定删除该收藏商品吗？' + '</div>', { title: '温馨提示' }, {
    draggable: true,
    dangerouslyUseHTMLString: true,
    customClass: 'custom-message-box',
    customStyle: dialogCustomStyle({ width: '385px' }),
    showClose: false,
  }).then((action) => {
    appPersonalDelLikeGet({
      params: {
        ids: props.item.id,
      }
    }).then((res) => {
      proxy.$modal.msgSuccess('删除成功')
      emit('reload')
    }).catch((err) => {
    })
  }).catch(() => { })
}

const isDisabled = computed(() => {
  return props.item.shopId === '2' ? false : props.item.price === 0
})

const state = reactive({
  isVisible: false,
  disabled: true,
})
const countFormRef = ref(null)
const countLoading = ref(false)
const countForm = reactive({
  count: 1, // 数量 string-body
  skuId: '' // 商品id string-body
})
const countRules = {
  count: [{ required: true, trigger: "change", message: "请选择添加数量" }]
}
const handleCommand = (type, e) => {
  if (type === 'close') {
    state.isVisible = false
  } else if (type === 'addShopCar') {
    countForm.count = 1
    countForm.skuId = e.id
    state.isVisible = true
  }
}
const countFormSubmit = () => {
  countFormRef.value.validate((valid) => {
    if (valid) {
      countLoading.value = true
      appViewAddCarsGet({
        params: countForm
      }).then((res) => {
        countLoading.value = false
        state.isVisible = false
        proxy.$modal.msgSuccess('成功加入购物车')
        useShoppingCartStore().init()
      }).catch((err) => {
        countLoading.value = false
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.goods {
  width: 247px;
  border: 1px solid var(--jbc-border-color);
  margin-top: 15px;
  margin-left: 15px;

  &:nth-child(4n+1) {
    margin-left: 0;
  }

  &.presale {
    margin-top: 20px;
    margin-left: 19px;

    &:nth-child(4n+1) {
      margin-left: 19;
    }

    &:nth-child(5n+1) {
      margin-left: 0;
    }
  }

  &-img {
    padding: 29px 29px 29px 30px;
    position: relative;
    cursor: pointer;
  }

  &-tag {
    position: absolute;
    left: 0;
    top: 0;
    font-size: 12px;
    color: #FFFFFF;
    line-height: 16px;
    border-radius: 0px 0px 16px 0px;
    padding: 3px 10px 5px 5px;

    &__0 {
      background: #F78D00;
    }

    &__1 {
      background: #0FCEA4;
    }

    &__2 {
      background: #4B4949;
    }

    &__3 {
      background: #D6000F;
    }
  }

  &-title {
    padding: 12px 19px;
    height: 52px;
    box-sizing: content-box;
  }

  &-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 19px 20px;

    .el-button--default {
      --el-font-size-base: 22px
    }
  }

  &-price {
    font-size: 20px;
    color: var(--jbc-color);

    &.normal {
      color: #999999;
    }
  }

  .shop-car {
    width: 20px;
    height: 20px;
  }

  &-presale {
    padding: 6px 19px;
    font-size: var(--jbc-font-size-extra-small);
    color: var(--jbc-font-color-light);
    line-height: 16px;

    & div~div {
      margin-top: 6px;
      font-size: var(--jbc-font-size-extra-small);
      color: var(--jbc-font-color-light);
    }
  }
}
</style>